// packageC/orders/Lottery/Lottery.js
var app = getApp();
const DrainageScene = require('../../../utils/drainage_scene.js')

Page({

  /**
	 * 页面的初始数据
	 */
  data: {
    goods:[],
    radio: '',
    zIndex:999,
    show:false,
    swiperName: {
      // 获奖名单
      loop: true, // 当获奖人数大于等于5的时候滚动，否则不滚动
      direction: "vertical",
      slidesPerView: 5,
      freeMode: true,
      freeModeMomentum: true,
      freeModeMomentumVelocityRatio: 1,
      autoplay: 1000,
    },
    // mobile: '15114785236',
    prizeIndex: 999,
    arrNum: [0, 1, 2, 3, 7, 11, 15, 14, 13, 12, 8, 4], // 定义转动的顺序
    clickFlage: true, // 点击事件，防止重复点击
    prizeInfoShow: false, // 显示中奖信息的遮罩层
    noPrizeShow: false, // 没中奖
    havePrizeShow: false, // 中奖了
    haveLottery: false, // 已经抽过奖了
    timer1: "",
    timer2: "",
    s1: "",
    s2: -1,
    lotteryId: "", // 抽奖活动的id
    activityModel: {}, // 活动说明
    hasRecord: false, // 是否显示获奖情况
    remainingTimes: 0, // 剩余抽奖次数
    prizeList: [], // 奖项列表
    prizeLevel: "", // 中奖等级
    prizeName: "", // 奖品名称
    prizeUrl: "", // 奖品图片
    prizers: [], // 获奖名单
    timeFlag: 0, // 时间标记，抽奖请求时间过长，则返回错误
    startStatus: 1, // 活动开始的状态
    prizerListBol: false,
    lotteryInfo: {},
    prizeInfo: {},
    love:0,
    amount_word: "",
    love_word: "",
    point_word: "",
    toolbar: false,
    empty_prize_prompt: "", //未中奖提示
    share_id:''
  },

  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(options) {
    if (options.mid) {
      app._setMid(options.mid);
    }
    if(options.share_id){
      this.setData({
        share_id:options.share_id
      });
    }
    console.log(this.data.share_id);
    if (options.lotteryId) {
      this.setData({
        lotteryId: options.lotteryId
      });
    }
    this.getData();
  },

  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function() {

  },

  /**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function() {

  },

  /**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function() {

  },

  /**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function() {

  },

  /**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
  onPullDownRefresh: function() {

  },

  /**
	 * 页面上拉触底事件的处理函数
	 */
  onReachBottom: function() {

  },

  /**
	 * 用户点击右上角分享
	 */
  onShareTimeline: function () {
    let value = wx.getStorageSync('yz_uid');
    let mid = '';
    if (value) {
      mid = value;
    }
    return {
      query: 'lotteryId=' + this.data.lotteryId + '&mid=' + mid
    };
  },

  /**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function(res) {
    var value = wx.getStorageSync('yz_uid');
    var mid = '';
    if (value) {
      mid = value;
    }
    // if (res && res.from === 'menu') {
    //   // 来自右上角转发按钮
    //   this.getShare();
    //   console.log("target menu");
    // }
    return {
      path: '/packageC/orders/Lottery/Lottery?lotteryId=' + this.data.lotteryId + '&mid=' + mid + '&share_id=' + mid,
    };
  },
  confirmGoods() {
    this.setData({
      show:false
    });
    if(this.data.radio){
      wx.navigateTo({
        url: '/packageA/detail_v2/detail_v2?id=' + this.data.radio
      });
    }
  },
  // getShare(){
  //   let that = this;
  //   let urlStr = app.getNetAddresss("plugin.lucky-draw.frontend.draw.getShare");
  //   app._getNetWork({
  //     url: urlStr,
  //     data: {
  //       lotteryId: this.data.lotteryId
  //     },
  //     success: function (resdata) {
  //       var res = resdata.data;
  //       if (res.result == 1) {
  //         that.getData();
  //       }
  //     },
  //     fail: function (res) {
  //       console.log(res);
  //     }
  //   });
  // },
  getData() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.lucky-draw.frontend.draw.index");
    if(this.data.share_id){
      // 如果有share_id传给后端抽奖次数加1
      urlStr += '&share_id='+this.data.share_id;
    }
    app._getNetWork({
      url: urlStr,
      data: {
        lotteryId: this.data.lotteryId
      },
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            shop_logo: res.data.shop_logo,
            amount_word: res.data.amount_word,
            love_word: res.data.love_word,
            point_word: res.data.point_word,
            credit1: res.data.point.credit1,
            success_mini_url: res.data.activityModel.success_mini_url,
            goods: res.data.goods,
            activityModel: res.data.activityModel,
            remainingTimes: res.data.surplus_time
          });
          if(res.data.love){
            that.setData({
              love:res.data.love[0],
            });
          }
          if(res.data.goods && res.data.goods.length>0){
            that.setData({
              radio: res.data.goods[0].id
            });
          }
          res.data.result_arr.forEach(item => {
            item.bgSrc = "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/lottery/item_bg.png";
          });
          res.data.result_arr.splice(5, 0, " ");
          res.data.result_arr.splice(6, 0, " ");
          res.data.result_arr.splice(9, 0, " ");
          res.data.result_arr.splice(10, 0, " ");
          that.setData({
            prizeList: res.data.result_arr,
            prizers: res.data.list
          });
          let temp = that.data.prizeList[4];
          that.setData({
            'prizeList[4]': that.data.prizeList[7],
            'prizeList[7]': temp
          });
          temp = that.data.prizeList[12];
          that.setData({
            'prizeList[12]': that.data.prizeList[13],
            'prizeList[13]': temp
          });
          temp = that.data.prizeList[14];
          that.setData({
            'prizeList[14]': that.data.prizeList[15],
            'prizeList[15]': temp
          });
          that.statusFun(
            Date.parse(new Date()) / 1000,
            that.data.activityModel.countdown_time[0],
            that.data.activityModel.countdown_time[1]
          ); // 获取状态，开始，未开始，结束
          if (that.data.prizers && that.data.prizers.length > 5) {
            that.setData({
              prizerListBol: true
            });
          }
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  statusFun(c, s, e) {
    if (c < s) {
      // 当前时间小于开始时间，未开始
      this.setData({
        startStatus: 0
      });
    } else if (c > s && c < e) {
      // 当前时间大于开始时间，并且小于结束时间，已经开始未结束
      this.setData({
        startStatus: 1
      });
    } else if (c > e) {
      // 当前时间大于结束时间，已经结束
      this.setData({
        startStatus: 2
      });
    }
  },
  prizeZhuan() {
    this.setData({
      prizeIndex: 0
    });
    if(this.data.activityModel.draw_type == 0){
      this.luckdraw();
      return false;
    }
    let name_key = "use_point",quantity = "point_word",total = "credit1";
    if (this.data.activityModel.draw_type == 2) {
      name_key = "use_love";
      quantity = "love_word";
      total = "love";
    }
    let count = Number(this.data.activityModel[name_key]);
    let total_count = Number(this.data[total]);
    let message = `抽奖需要消耗${count}${this.data[quantity]}，是否继续？`;
    wx.showModal({
      title:"提示",
      content:message,
      success:({confirm})=>{
        if(confirm){
          if(count>total_count){
            app.tips(this.data[quantity] + "不足")
            return
          }else {
            this.luckdraw();
          };
        }
      }
    })
  },
  luckdraw(){
    let that = this;
    if (this.data.remainingTimes > 0) {
      // 判断剩余抽奖次数
      if (this.data.clickFlage) {
        if (this.data.startStatus === 1) {
          let isBindDrainageScene = DrainageScene.bindDrainageScene({
            scene: 7,
            title: '抽奖'
          });
          if(!isBindDrainageScene) return;//爆客码绑定场景

          // 活动开始
          this.setData({
            clickFlage: false, // 不能点击
            timer1: setInterval(()=>{this.move();}, 100)
          });
          let urlStr = app.getNetAddresss("plugin.lucky-draw.frontend.draw.doDraw");
          app._getNetWork({
            url: urlStr,
            data: {
              lotteryId: this.data.lotteryId
            },
            success: function(resdata) {
              var res = resdata.data;
              if (res.result == 1) {
                that.setData({
                  remainingTimes: that.data.remainingTimes - 1
                });
                if (res.data.result) {
                  that.setData({
                    hasRecord: true,
                    prozeLevel: res.data.result.item,
                    prizeName: res.data.result.prize,
                    prizeUrl: res.data.result.thumb_url
                  });
                  // 更新页面数据 任务：#71863
                  that.getData();
                } else {
                  // 更新页面数据 任务：#71863
                  that.getData();
                  that.setData({
                    hasRecord: false,
                    prozeLevel: res.data.item,
                    prizeName: res.data.prize,
                    prizeUrl: res.data.thumb_url,
                    empty_prize_prompt: res.data.empty_prize_prompt
                  });
                }
                setTimeout(() => {
                  clearInterval(that.data.timer1);
                  that.lowSpeed();
                }, 1200);
              } else {
                wx.showModal({
                  title: "提示",
                  content: res.msg,
                  showCancel: false,
                  success(res_1) {
                    if (res_1.confirm) {
                      if(that.data.goods && that.data.goods.length>0){
                        that.setData({
                          show:true
                        });
                      }
                    }
                  },
                });
                that.setData({
                  clickFlage: true // 不能点击
                });
                clearInterval(that.data.timer1);
                clearInterval(that.data.timer2);
              }
            },
            fail: function(res) {
              console.log(res);
            }
          });
          // 请求，返回后给s定值
        } else if (this.data.startStatus === 0) {
          // 没开始
          wx.showToast({
            icon: 'none',
            title: '活动尚未开始',
            duration: 1500
          });
        } else if (this.data.startStatus === 2) {
          // 已经结束
          wx.showToast({
            icon: 'none',
            title: '活动已经结束',
            duration: 1500
          });
        }
      }
    } else {
      // 没有抽奖机会了
      this.setData({
        prizeInfoShow: true,
        haveLottery: true
      });
    }
  },
  // 降速
  lowSpeed() {
    clearInterval(this.data.timer1);
    this.setData({
      clickFlage: false, // 不能点击
      timer2: setInterval(()=>{this.move();}, 300)
    });
    setTimeout(() => {
      // 顺序打乱
      this.setData({
        s2: this.data.prozeLevel
      });
    }, 900);
  },
  move() {
    if (this.data.prizeIndex === 0) {
      this.setData({
        prizeIndex: this.data.prizeIndex + 1
      });
    } else if (this.data.prizeIndex === 12) {
      this.setData({
        prizeIndex: 0
      });
    } else {
      this.setData({
        prizeIndex: this.data.prizeIndex + 1
      });
    }
    if (
      this.data.s2 !== -1 &&
			(this.data.prizeList[this.data.arrNum[this.data.prizeIndex]] && this.data.prizeList[this.data.arrNum[this.data.prizeIndex]].item == this.data.s2)
    ) {
      clearInterval(this.data.timer1);
      clearInterval(this.data.timer2);
      this.stop();
    }
    this.setData({
      timeFlag: this.data.timeFlag + 100
    });
    if (this.data.timeFlag >= 10000 && !this.data.prizeName) {
      clearInterval(this.data.timer1);
      clearInterval(this.data.timer2);
      wx.showToast({
        icon: 'none',
        title: '当前抽奖人数过多，稍后再来',
        duration: 1500
      });
      this.setData({
        clickFlage: true
      });
    }
  },
  // 停止
  stop() {
    this.setData({
      s2: -1,
      clickFlage: false
    });
    this.prizeInfo(); // 弹出是否中奖
  },
  prizeInfo() {
    setTimeout(() => {
      this.setData({
        clickFlage: true
      });
      if (this.data.hasRecord) {
        this.setData({
          prizeInfoShow: true,
          havePrizeShow: true
        });
      } else {
        this.setData({
          prizeInfoShow: true,
          noPrizeShow: true
        });
      }
    }, 800);
  },
  lotteryRecord() {
    wx.navigateTo({
      url: '/packageC/orders/LotteryRecord/LotteryRecord?lotteryId=' + this.data.lotteryId
    });
  },
  onChange(event) {
    this.setData({
      radio: event.detail,
    });
  },
  closePop(){
    this.setData({
      show:false
    });
  },
  close(e) {
    let that=this;
    let name=e.currentTarget.dataset.name;
    //关闭没中奖
    this.setData({
      prizeInfoShow: false,
      noPrizeShow: false,
      haveLottery: false,
      havePrizeShow: false
    });
    if(name=='success'){
      if (that.data.success_mini_url){
        //要延时执行的代码
        wx.navigateTo({
          url: that.data.success_mini_url,
        });
      }
    }
  },
  goIndex() {
    //preferIndex
    this.setData({
      prizeInfoShow: false, // 显示中奖信息的遮罩层
      noPrizeShow: false
    });
    wx.reLaunch({
      url: '/packageG/index/index'
    });
  },
  showToolbar() {
    this.setData({
      toolbar: !this.data.toolbar
    });
  },
  // 跳转主页
  gotoHome() {
    wx.reLaunch({
      url: '/packageG/index/index'
    });
  },
  // 跳转个人中心
  gotoMember() {
    wx.reLaunch({
      url: '/packageG/member_v2/member_v2'
    });
  },
});
